//Alberto De Pena
//Kyle Weaver
//Aldo Campos
//Alex yang

#ifndef NIM_HEADER
#define NIM_HEADER
#include "nim.h";
#endif

#ifndef IOSTREAM
#define IOSTREAM
#include <iostream>
#endif
#include <string.h>
using namespace std;

struct host_s 
{
	char name[MAX_NAME+1];
	char host[MAX_HOST+1];
	char port[MAX_SERVICE+1];
};

void client_main ( int argc, char** argv ) 
{
	host_s server[100];

	char recvBuf[MAX_RECV_BUF+1];
	char sendBuf[MAX_SEND_BUF+1];
	char host[MAX_HOST+1];
	char hPort[MAX_SERVICE+1];
	char service[MAX_SERVICE];
	char local_user[1024];
	
	cout << "What is your name? ";
	cin.getline(local_user,MAX_LINE);

	SOCKET s = connectsock(BROADCAST_ADDR,"","UDP");
	if (s != INVALID_SOCKET) 
	{
		strcpy_s(service,MAX_SERVICE,UDPPORT_NIM);
		strcpy_s(sendBuf,MAX_SEND_BUF,"Name?\0");
		
		int len = udp_send(s,sendBuf,(int)strlen(sendBuf)+1,BROADCAST_ADDR,service);
		if (len > 0) 
		{
			int count = 0;
			cout << "Building list of available games..." << endl;
			int stat = wait(s,5,0);
			
			while (stat > 0) 
			{
				len = udp_recv(s,recvBuf,MAX_RECV_BUF,host,hPort);
				if (len > 0)
				{
					strcpy_s(server[count].host,MAX_HOST,host);
					strcpy_s(server[count].name,MAX_NAME,recvBuf);
					strcpy_s(server[count].port,MAX_SERVICE,hPort);
					count++;					
				}
				stat = wait(s,5,0);
			}

			cout << "List of available hosts:" << endl << endl;
			int i=0;
			while(i<count)
			{
				cout << i + 1 << ") " << server[i].name << endl;
				i++;
			}
			
			int serverChoice;
			cout << endl << "Who would you like to challenge? " << "(1-" << count << "; 0 = None)? ";
			cin >> serverChoice;
			if( serverChoice > 0)
			{
					char msg[1024] = "Play? Name=";
					strcat_s(msg,1023,local_user);
					strcpy_s(sendBuf,MAX_SEND_BUF,msg);

					len = udp_send(s,sendBuf,(int)strlen(sendBuf)+1,server[serverChoice - 1].host,server[serverChoice - 1].port);
					int stat1 = wait(s,5,0);
					while(stat1 > 0)
					{
						strcpy_s(recvBuf,MAX_SEND_BUF,"\0");
						len = udp_recv(s,recvBuf,MAX_RECV_BUF,host,hPort);
						if( len > 0 )
						{
							if( _stricmp(recvBuf,"YES") == 0)
							{
								strcpy_s(sendBuf,MAX_SEND_BUF,"Great!\0");
								len = udp_send(s,sendBuf,(int)strlen(sendBuf)+1,server[serverChoice - 1].host,server[serverChoice - 1].port);
								

								strcpy_s(service,MAX_SERVICE,TCPPORT_NIM);
								SOCKET socket =connectsock(server[serverChoice - 1].host,service,"tcp");
								play_Nim(socket,true,host);
								closesocket(socket);
							}
						}
						stat1 = wait(s,5,0);
					}
					closesocket(s);
					strcpy_s(recvBuf,MAX_RECV_BUF,"\0");
					strcpy_s(sendBuf,MAX_SEND_BUF,"\0");
			}
		}
	}
}